import setTableColumn from '@/components/common/setTableColumn'
import coverApi from '@api/cover'


export default {
  data() {
    return {
      showColumns: [],
      menuColumnId: '',
      showTable: false,
      columnHandle: {
        title: '',
        fixed: 'right',
        width: '30px',
        key: '',
        renderHeader: (h) => {
          return h('div',
            [
              h('Icon', {
                props: {
                  type: 'md-settings'
                },
                class: ['handle-cus'],
                on: {
                  click: this.setTableColumn
                }
              })
            ]
          )
        },
      }
    }
  },
  async mounted() {
    const res = await this.getTableColumn()
    this.handleRemoteColumn(res)
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    deleteField(fieldArr, field) {
      let temp = [...fieldArr]
      if (!temp || !Array.isArray(temp)) {
        return
      } else {
        temp.forEach((item, index) => {
          if(item.columnKey == field) {
            temp.splice(index, 1)
          }
        })
        return temp
      }
    },
    getTableColumn() {
      this.showTable = false
      return coverApi.getColumnInfo({ menuNo: this.menuNo })
    },
    getFormatColumn(item){
      let minWidth = null
      if (item.minWidth) minWidth = item.minWidth
      if (item.width) minWidth = item.width
          // 包含时间的字段统一处理宽度
      if(item.columnKey.includes('Time') || item.columnKey.includes('Date')) { minWidth = 170 }
      let column = this.columnList.find(n => n.columnKey === item.columnKey)
      return {
        key: item.columnKey,
        title: item.columnName,
        width: minWidth,
        render: column ? column.render : ()=>{},
        // width: item.width
      }
    },
    getChildrenArr(item) {
      if (item.children) {
        let arr = []
        item.children.forEach(child => {
          arr.push(this.getChildrenArr(child))
        })
        return { title:item.columnName,
                  align: item.align,
                  children: arr}
      } else {
        return this.getFormatColumn(item)
      }
    },
    handleRemoteColumn(res) {
      if (res.data && res.data.settingInfo) {
        this.menuColumnId = res.data.id
        this.showColumns = JSON.parse(res.data.settingInfo)
        // this.showColumns = JSON.parse('[{"columnName":"任务安排","align":"center","children":[{"columnName":"举措大类","columnKey":"stype","width":"120"},{"columnName":"举措细类","columnKey":"mtype","width":"120"},{"columnName":"重点任务","columnKey":"highTask","width":"250"}]},{"columnName":"2024年任务计划","align":"center","children":[{"columnName":"重要程度","columnKey":"stype","width":"120"},{"columnName":"落实举措","columnKey":"taskMod","width":"120"},{"columnName":"预期成果","columnKey":"highTask","width":"120"},{"columnName":"成果关键指标","align":"center","children":[{"columnName":"指标名称","columnKey":"stype","width":"150"},{"columnName":"指标说明和计算方法","columnKey":"stype","width":"200"},{"columnName":"xx年预期指标","columnKey":"stype","width":"200"}]},{"columnName":"责任部门/单位","columnKey":"highTask","width":"200"}]},{"columnName":"2024年任务完成情况","align":"center","children":[{"columnName":"是否完成","columnKey":"stype","width":"100"},{"columnName":"取得成果","columnKey":"mtype","width":"200"},{"columnName":"成功关键指标2023年底指标值","columnKey":"highTask","width":"200"},{"columnName":"备注","columnKey":"todo","width":"200"},{"columnName":"状态","columnKey":"wfStatusName"}]}]')
        // 为了处理历史脏数据，数据汇总页面，强制删除状态列
        if (this.fromPage != 'creater') {
          this.showColumns.forEach((item, index) => {
            if(item.columnKey == 'wfStatusName') {
              this.showColumns.splice(index, 1)
            }
          })
        }
        const selectItem = this.pageTableConfig.columns.find(item => item.type === 'selection')
        const handleItem = this.pageTableConfig.columns.find(item => item.title === '操作')
        let handleColumn = []
        if (handleItem) handleColumn = [handleItem]
        this.showColumns = this.showColumns.filter(item => !!item)
        let menus= this.showColumns.map(item => {
          return this.getChildrenArr(item)
        })
        this.pageTableConfig.columns = menus.concat(handleColumn, [this.columnHandle]);
        if (selectItem) this.pageTableConfig.columns.unshift(selectItem)
      } else {
        // this.showColumns = JSON.parse(JSON.stringify(this.defaultColumns))
        this.pageTableConfig.columns.forEach(item => {
          if (item.key) {
            this.showColumns.push({
              columnName: item.title,
              columnKey: item.key
            })
          }
        })
        this.pageTableConfig.columns.push(this.columnHandle)
      }
      this.showTable = true
    },
    setTableColumn() {
      new this.$pageModal(
        setTableColumn,
        {
          props: {
            list: this.columnList,
            initColKeyList: this.showColumns
          }
        },
        async (data) => {
          if (data && !this.menuColumnId) {
            const params = {
              settingInfo: JSON.stringify(this.saveColumn(data)),
              menuNo: this.menuNo
            }
            await coverApi.insertColumn(params)
          } else if (data && this.menuColumnId) {
            const params = {
              settingInfo: JSON.stringify(this.saveColumn(data)),
              menuNo: this.menuNo,
              id: this.menuColumnId
            }
            await coverApi.updateColumn(params)
          }
          if (!data) return
          this.$message.success('操作成功')
          const res = await this.getTableColumn()
          this.handleRemoteColumn(res)
          this.$nextTick(() => {
            this.init()
          })
        }
      )
    },
    saveColumn(data) {
      let list = data.filter(item => {
        // 兼容老数据，columnList里面可能没有之前脏数据中设置的字段
        let column = this.columnList.find(n => n.columnKey === item)
        return !!column
      })
      list = list.map(item => {
        let column = this.columnList.find(n => n.columnKey === item)
        return {
          columnKey: item,
          columnName: column.columnName,
          minWidth: column.minWidth,
          width: column.width
        }
      })
      return list.sort((a, b) => {
        const indexA = this.columnList.findIndex(item => item.columnKey === a.columnKey)
        const indexB = this.columnList.findIndex(item => item.columnKey === b.columnKey)
        return indexA - indexB
      })
    }
  }
}
